<template>
  <div class="app-container">
    <el-row style="margin-bottom:30px;">
      <!-- 搜索区域 -->
      <el-card style="margin:0 0 5px 5px;" v-show="showSearch">
        <el-form ref="queryForm" :inline="true" :model="queryData">
          <el-form-item label="订单号" prop="Q_orderSn_S_LK">
            <el-input v-model="queryData.Q_orderSn_S_LK" placeholder="订单号" />
          </el-form-item>
          <el-form-item label="优惠券名称" prop="couponName">
            <el-select
              v-model="queryData.Q_couponId_L_EQ"
              v-el-select-load-more="loadMoreCouponQuery"
              ref="coupon_select"
              filterable
              remote
              reserve-keyword
              placeholder="请输入优惠券名称"
              :remote-method="onSearchCoupon"
              :loading="loadingCouponQuery">
              <el-option
                v-for="item in optionOfCoupons"
                :key="item.id"
                :label="item.couponName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="使用状态" prop="Q_useStatus_S_EQ">
            <el-select v-model="queryData.Q_useStatus_S_EQ" placeholder="使用状态">
              <el-option
                v-for="item in optionOfStatus"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="fr p-r-10">
            <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
            <el-button class="filter-item m-l-10" type="info" round icon="el-icon-refresh" @click="handleClear">
              清空
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- table区域 -->
      <el-card class="m-l-5">
        <el-button v-permission="['mall:coupon:history']" v-if="selectionData.length > 0" class="m-b-10 m-l-10" type="danger" icon="el-icon-delete" @click="handleDelete()">
          删除
        </el-button>
        <table-toolbar :showSearch.sync="showSearch" @refresh="getTableData"/>
        <el-table
          ref="queryTable"
          v-loading="tableLoading"
          row-key="id"
          :data="tableData"
          element-loading-text="加载中"
          border
          fit
          highlight-current-row
          show-overflow-tooltip
          height="100px"
          v-el-height-adaptive-table="{bottomOffset: 110}"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40"/>
          <el-table-column align="center" label="订单号" prop="orderSn" width="260" show-overflow-tooltip />
          <el-table-column align="center" label="优惠卷名称" prop="couponName" show-overflow-tooltip />
          <el-table-column align="center" label="会员名字" prop="nickName" width="180" show-overflow-tooltip />
          <el-table-column align="center" label="获取方式" prop="couponType" sortable width="120">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.couponType === '0'" type="success" text="后台赠送" />
              <el-tag v-if="scope.row.couponType === '1'" type="primary" text="主动领取" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="创建时间" prop="createTime" width="180" show-overflow-tooltip />
          <el-table-column align="center" label="使用时间" prop="useTime" width="180" show-overflow-tooltip />
          <el-table-column align="center" label="使用状态" prop="useStatus" sortable width="180">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="light" :content="getDictValue('status', scope.row.useStatus)" placement="top">
                <el-link :type="getDictColor('status', scope.row.useStatus)" :underline="false"><i :class="'el-icon-'+getDictType('status', scope.row.useStatus)"></i></el-link>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column  v-permission="['mall:coupon:history']" align="center" label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <el-link type="danger" icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData"/>
      </el-card>
    </el-row>
  </div>
</template>

<script>
import { couponHistoryTable, couponHistoryDelete } from '@/api/mall/coupon/history'
import { couponSelect } from '@/api/mall/coupon/manage'
import Pagination from '@/components/Pagination'

export default {
  components: {
    Pagination
  },
  directives: {
    'el-select-load-more': {
      bind(el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECT_WRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
        SELECT_WRAP_DOM.addEventListener('scroll', function() {
          /**
           * scrollHeight 获取元素内容高度(只读)
           * scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
           * clientHeight 读取元素的可见高度(只读)
           * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
           * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
           */
          const condition = this.scrollHeight - this.scrollTop <= this.clientHeight
          if (condition) {
            binding.value()
          }
        })
      }
    }
  },
  data() {
    return {
      showSearch: true,
      queryData: {
        Q_orderSn_S_LK: undefined,
        Q_couponId_L_EQ: undefined,
        Q_useStatus_S_EQ: undefined
      },
      loadingCouponQuery: false,
      couponQueryTerm: undefined,
      couponQueryPage: 1,
      couponQueryLength: 20,
      couponQueryMore: false,
      optionOfCoupons: [],
      optionOfStatus: [],
      tableData: [],
      tableLoading: false,
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: undefined,
        order: undefined
      },
      selectionData: []
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // 加载下拉菜单
      this.getDictData()
      this.getTableData()
    },
    getDictData() {
      this.$dictGroup('sys_use_status').then(response => {
        this.optionOfStatus = response
      })
    },
    getDictType(property, value) {
      let option = this.getOptions(property)
      return this.$api.getDictElement(option, value)[0]
    },
    getDictValue(property, value) {
      let option = this.getOptions(property)
      return this.$api.getDictElement(option, value)[1]
    },
    getDictColor(property, value) {
      let option = this.getOptions(property)
      return this.$api.getDictElement(option, value)[2]
    },
    getOptions(property) {
      if ('status' === property) {
        return this.optionOfStatus
      }

      return []
    },
    onSearchCoupon(query) {
      this.loadingCouponQuery = true
      this.couponQueryPage = 1
      this.couponQueryTerm = query
      this.optionOfCoupons = []
      this.getCouponQueryData()
      this.couponQueryPage++
      this.loadingCouponQuery = false
    },
    getCouponQueryData() {
      couponSelect({
        term: this.couponQueryTerm, // 输入值
        page: this.couponQueryPage, // 页码
        length: this.couponQueryLength
      }).then(response => {
        this.optionOfCoupons = [...this.optionOfCoupons, ...response.param.data]
        this.couponQueryMore = (this.couponQueryPage * this.couponQueryLength) < response.param.total
      }).catch(e => {})
    },
    loadMoreCouponQuery() {
      if (this.couponQueryMore) {
        this.couponQueryPage++
        this.getCouponQueryData()
      }
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getTableData()
    },
    handleClear() {
      this.$refs.queryForm.resetFields()
      this.getTableData()
    },
    getTableData() {
      const query = Object.assign(this.tableQuery, this.queryData)
      this.tableLoading = true
      couponHistoryTable(query).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
        this.$refs.queryTable.bodyWrapper.scrollTop = 0
      }).catch(e => {
        this.tableLoading = false
      })
    },
    sortChange(data) {
      const {prop, order} = data
      this.tableQuery.sort = prop
      if (order === 'ascending') {
        this.tableQuery.order = 'asc'
      } else {
        this.tableQuery.order = 'desc'
      }
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.selectionData = val
    },
    handleDelete(id) {
      const ids = this.selectionData.map(function (session, index) {
        return session.id
      }).join(',')

      id = id || ids
      if (!id || id.length === 1) {
        this.$modal.msgWarning('请先选中数据项')
        return
      }

      this.$confirm('是否删除所选数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        couponHistoryDelete({ids: id}).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess(response.msg)
        }).catch(e => {
        })
      }).catch(e => {
      })
    }
  }
}
</script>

<style scoped>
.line {
  text-align: center;
}
</style>
